package com.baizhi.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
@Component
public class CGLIBProxyUtil {

    @Autowired
    private UserService userService ;


    @Bean
    public UserService getProxy(final UserService userService){
     this.userService = userService;


        //新建增强器
        Enhancer enhancer = new Enhancer();

        enhancer.setSuperclass(userService.getClass());

        enhancer.setCallback(new MethodInterceptor() {
            @Override
            public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {

                System.out.println("开启日志");
                System.out.println("检查权限");

                UserService ac = (UserService) method.invoke(userService, objects);

                System.out.println("统计时间");

                return ac;
            }
        });

        return (UserService) enhancer.create();
    }
}
